package com.zz.comframe.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import treemap.zz.json.JSONArray;

import com.zz.comframe.CommonDataProcesser;
import com.zz.comframe.MD5;
import com.zz.comframe.properties.PropertiesPool;

public class CheckMember extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		if (!PropertiesPool.CheckRequestParameters(request)) {
			out.print("{\"success\":false,\"errors\":[{\"id\":\"checkcode\",\"msg\":\"请求中含有非法字符！\"}]}");
			return;
		}

		// 设置跳转页面为欢迎页面
		String path = "index.jsp";

		// 检验是否已登录
		if (request.getSession().getAttribute("user1") != null) {
			out.print("{\"success\":true,\"url\":\"" + path + "\"}");
			return;
		}

		String username = request.getParameter("user") == null ? (String) request.getAttribute("user") : request.getParameter("user");
		String password = request.getParameter("pass") == null ? (String) request.getAttribute("pass") : request.getParameter("pass");
		String savecookie = request.getParameter("saved");
		String code = request.getParameter("checkcode") == null ? (String) request.getAttribute("checkcode") : request.getParameter("checkcode");
		String scode = (request.getSession().getAttribute("validate_code")).toString();
		String md5oper = (request.getSession().getAttribute("md5_oper")).toString(); // md5算子，与库中密码连接后md5加密再与form中密码比较

		this.username = username;
		this.password = password;
		this.orbit = null;

		// String result = "{\"success\":false,\"errors\":[";
		// 判断用户名、密码的合法性
		if (!(this.isEmpty())) {

			// 用户名、密码不为空，验证
			try {
				// 判断验证码
				if (scode == null || "".equals(scode) || code == null || "".equals(code) || !(scode.equals(code))) {
					out.print("{\"success\":false,\"errors\":[{\"id\":\"imgcode\",\"msg\":\"验证码不付!\"}]}");
					return;
				}

				CommonDataProcesser dp = new CommonDataProcesser();
				String sql = PropertiesPool.getCommonpro("SQL_SELECT_USERNAME") + " where col1='" + this.username + "' ";//and col2='" + this.password + "' ";
				JSONArray jun = dp.getObjectListAll(sql); // 

				//不存在用户
				if (jun.length() <= 0) {
					out.print("{\"success\":false,\"errors\":[{\"id\":\"user\",\"msg\":\"用户名不存在!\"}]}");
					return;
				}
            	MD5 md5 = new MD5();
            	String tmp = md5.getMD5ofStr(jun.getJSONObject(0).getString("col2")+md5oper);

				if (password.equalsIgnoreCase(tmp)) {
					// 合法用户
					this.orbit = jun.getJSONObject(0).getString("col3");
					// 设置session属性
					request.getSession().setAttribute("user1", this.username);
					// 用户权限
					request.getSession().setAttribute("userorbit", this.orbit);
					if ("on".equalsIgnoreCase(savecookie)||"true".equalsIgnoreCase(savecookie)) {

						// 如果选择了保存Cookie选项，则保存Cookie
						Cookie c1 = new Cookie("userinfo", this.username + md5oper + this.orbit);
						Cookie c2 = new Cookie("loginoper", md5oper);
						// 设置Cookie保存时间为2周
						c1.setMaxAge(14 * 24 * 60 * 60);
						c2.setMaxAge(14 * 24 * 60 * 60);
						response.addCookie(c1);
						response.addCookie(c2);
						c1.setPath("/");
						c2.setPath("/");
					}
					out.print("{\"success\":true,\"url\":\"" + path + "\"}");
					return;
				} else {
					out.print("{\"success\":false,\"errors\":[{\"id\":\"user\",\"msg\":\"用户名或密码错误!\"},{\"id\":\"pass\",\"msg\":\"用户名或密码错误!\"}]}");
					return;

					// errors.add("用户名或密码错误！");
				}
			} catch (Exception e) {
				String err = "";
				for (int i = 0; i < 3; i++) {
					err += this.errors[i] != null ? ",{\"id\":\"user\",\"msg\":\"" + this.errors[i] + "\"}" : "";
				}
				out.print("{\"success\":false,\"errors\":[" + err.substring(1) + "]}");
			}
		} else { // isEmpty() true
			String err = "";
			for (int i = 0; i < 3; i++) {
				err += this.errors[i] != null ? ",{\"id\":\"user\",\"msg\":\"" + this.errors[i] + "\"}" : "";
			}
			out.print("{\"success\":false,\"errors\":[" + err.substring(1) + "]}");
		}
		// 保存错误信息
		// request.setAttribute("errors", errors);
		// 保存用户信息
		// request.setAttribute("member", mem);
		// 跳转
		//request.getRequestDispatcher(path).forward(request, response);
	}

	private String username;
	private String password;
	private String orbit;
	private String[] errors = { null, null, null };

	public boolean isEmpty() {

		boolean iserror = false;
		if (this.username == null || "".equals(this.username)) {

			iserror = true;
			this.errors[0] = "用户名不能为空！";
		}
		if (this.password == null || "".equals(this.password)) {

			iserror = true;
			this.errors[1] = "密码不能为空！";
		}
		return iserror;
	}
}
